require("behaviours/wander")
require("behaviours/doaction")
require("behaviours/chaseandram")
require("behaviours/chaseandattack")
require("behaviours/standandattack")
require("behaviours/leash")

local MAX_CHASE_TIME = 10
local GIVE_UP_DIST = 20
local MAX_CHARGE_DIST = 60

local wandertimes =
{
    minwalktime = 5,
    randwalktime =  3,
    minwaittime = 0,
    randwaittime = 0,
}

local function GetWanderPos(inst)
    local target = inst:GetNearestPlayer(false) or inst
    return target:GetPosition()
end

local SEE_DIST = 40
local function BaseDestroy(inst)
    local target = FindEntity(inst, SEE_DIST, function(item)
        if item.components.workable and item:HasTag("structure")
            and item.components.workable.action == ACTIONS.HAMMER
            and item:IsOnValidGround() then
            return true
        end
    end)
    if target then
        return BufferedAction(inst, target, ACTIONS.HAMMER)
    end
end

local WalpurgisNightBrain = Class(Brain, function(self, inst)
    Brain._ctor(self, inst)
end)

function WalpurgisNightBrain:OnStart()
    local root =
        PriorityNode(
        {
            WhileNode(function() return self.inst.sg:HasStateTag("running") or
                (self.inst.components.combat.target and self.inst.components.combat.target:GetPosition():Dist(self.inst:GetPosition()) >= TUNING.WALPURGISNIGHT_ATTACK_RANGE) end,
                "Charge Behaviours", ChaseAndRam(self.inst, MAX_CHASE_TIME, GIVE_UP_DIST, MAX_CHARGE_DIST)),
            WhileNode(function() return (self.inst.components.combat.target and self.inst.components.combat.target:GetPosition():Dist(self.inst:GetPosition()) < TUNING.WALPURGISNIGHT_ATTACK_RANGE) end, "Attack Behaviours", ChaseAndAttack(self.inst, nil, nil, nil, nil, true)),
            DoAction(self.inst, BaseDestroy, "DestroyBase", true),
            Wander(self.inst, GetWanderPos, 20, wandertimes),
        }, .25)

    self.bt = BT(self.inst, root)
end

return WalpurgisNightBrain
